package servlet;

import model.Type;
import org.apache.commons.beanutils.BeanUtils;
import service.TypeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/type_edit")
public class AdminTypeEditServlet extends HttpServlet {
    private TypeService tService = new TypeService();

    // 处理 GET 请求（跳转到修改页面）
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id")); // 获取类目 ID
        Type type = tService.select(id); // 根据 ID 查询类目信息
        request.setAttribute("type", type); // 将类目信息传递给 JSP 页面
        request.getRequestDispatcher("/admin/type_edit.jsp").forward(request, response); // 跳转到修改页面
    }

    // 处理 POST 请求（提交修改）
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Type t = new Type();
        try {
            BeanUtils.copyProperties(t, request.getParameterMap()); // 将表单数据映射到 Type 对象
            tService.update(t); // 更新类目信息
            request.setAttribute("msg", "类目信息更新成功！");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("failMsg", "类目信息更新失败！");
        }
        request.getRequestDispatcher("/admin/type_list").forward(request, response); // 返回类目列表
    }
}